package com.jysz.certificate.service;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import com.jysz.certificate.persistence.dao.CommonDao;
import com.jysz.certificate.utils.DateUtil;
import com.jysz.webcore.ssh.entity.AbstractBaseEntity;
import com.jysz.webcore.ssh.service.EntityService;

/**
 * 通用service
 * 
 * @author <a href="mailto:javaengine@outlook.com">Kaca Rich</a>
 *
 */
@SuppressWarnings("rawtypes")
@Service
public class CommonService extends EntityService<AbstractBaseEntity, Long, CommonDao>{
	
	@Resource
	private CommonDao commonDao;

	@Override
	public CommonDao getEntityDao() {
		return commonDao;
	}

	/**
	 * @param classType
	 * @param valProperty
	 * @param value
	 * @param value2 
	 * @param entityId
	 * @param sqlRestriction 
	 * @param valueType 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public boolean isUniqueProperty(String classTypes, String valProperty, String valPropertyType, String value,  Long entityId, String sqlRestriction, String valueType) {
		String [] classTypeArray = classTypes.split(",");
		int count = 0;
		

		Object oValue = value;
		
		if(StringUtils.isNotBlank(valueType)){
			try {
				Class valueClass = Class.forName(valueType);
				if(valueClass.isAssignableFrom(Date.class)){
					oValue = DateUtil.getDate(value, "yyyy-MM");
				}else if(valueClass.isAssignableFrom(Long.class)){
					if(oValue != null && StringUtils.isNumeric(oValue.toString())){
						oValue = Long.valueOf(oValue.toString());
					}else{
						oValue = 0;
					}
					
				}
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
		}
		
		if(StringUtils.isNotBlank(valPropertyType)){
			try {
				if(Class.forName(valPropertyType).isAssignableFrom(Date.class)){
					oValue = DateUtil.getDate(value, "yyyy-MM");
				}
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
		}
		
		for (int i = 0; i < classTypeArray.length; i++) {
			count += commonDao.findCountByClassType(classTypeArray[i], valProperty, oValue, entityId, sqlRestriction);
		}
//		int qty = entityId != null && entityId != 0 ? 2 : 1;
		return count < 1;
	}

	/**
	 * @param classType
	 * @param value
	 * @param displayFields
	 * @return
	 */
	public List findAutocompleteEntitys(String classType, String value, String displayFields, String filterSql) {
		return commonDao.findAll(classType, displayFields, value, filterSql);
	}


}
